<template>
  <div>
    <el-container style="max-width: 960px">
      <el-header style="margin-top: 10px;height: auto;">
        <el-row>
          <el-input
            v-model="kwInput"
            placeholder="输入 任意字符 进行筛选"
            class="input-with-select"
            clearable
            @keyup.native.enter="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" :loading="listLoading" @click="handleSearch">搜索</el-button>
          </el-input>
          <el-button
            type="primary"
            class="el-icon-plus add-btn"
            :disabled="listLoading"
            @click="handleAction('create', '添加')"
          >添加
          </el-button>
        </el-row>
      </el-header>
      <el-main>
        <el-table
          v-loading="listLoading"
          :data="data"
          border
          fit
          highlight-current-row
          style="width: 100%"
          @sort-change="handleSort"
        >
          <el-table-column prop="_serialized" label="名称" width="180" />
          <el-table-column prop="platform" label="platform" width="180" />
          <el-table-column prop="user.realname" label="使用人" width="180" />
          <el-table-column prop="create_at" label="创建时间" width="180">
            <template slot-scope="scope">
              <div>{{ scope.row.create_at }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <el-button
                v-show="!scope.row.edit"
                size="mini"
                icon="el-icon-edit"
                type="warning"
                plain
                @click="handleAction('edit', scope.row)"
              >修改
              </el-button>
              <el-button
                v-show="!scope.row.edit"
                size="mini"
                icon="el-icon-delete"
                type="danger"
                plain
                @click="handleAction('delete', scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>
    <el-dialog
      append-to-body
      :title="title"
      :width="width"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="120px">
        <el-form-item label="serialized号码">
          <el-input v-model="temp._serialized" placeholder="1234567890@c.us" />
        </el-form-item>
        <el-form-item label="plantform" prop="contact_name">
          <el-input v-model="temp.platform" />
        </el-form-item>
        <el-form-item label="使用员工" label-width="120px">
          <el-select v-model="temp.user_id" placeholder="使用人" filterable size="mini" clearable>
            <el-option
              v-for="item in projectUsers"
              :key="item.id"
              :label="item.first_name +item.last_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/crm/crmm'
import { CRMGetProjectUsers } from '@/api/crm/crmmanage'
import qs from 'qs'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Crmwhatsappconfig',
  data() {
    return {
      table_name: 'WhatsappConfig',
      data: [],
      listLoading: false,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      action: null,
      dialogVisible: false,
      title: '',
      inputVisible: false,
      inputValue: '',
      predefineColors: [
        '#6C6762',
        '#67C23A',
        '#F56C6C',
        '#ff4500',
        '#ff8c00',
        '#ffd700',
        '#00ced1',
        '#1e90ff',
        '#c71585'
      ],
      projectUsers: [],
      temp: {
        _serialized: '',
        platform: 'local',
        password: '',
        user_id: ''
      },
      apps: [
        {
          value: '邮件',
          label: '邮件',
          private: false
        },
        {
          value: '供应商产品',
          label: '供应商产品'
        },
        {
          value: '客户',
          label: '客户'
        }
      ],
      width: '',
      innerDialogVisible: false
    }
  },
  created() {
    this.handleCRMGetProjectUsers()
  },
  methods: {
    handleCRMGetProjectUsers() {
      CRMGetProjectUsers(qs.stringify({
        pagesize: 100,
        page: 1,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.projectUsers = response.data.data
        }).catch(err => {
          console.log(err)
        })
    },
    resetTemp() {
      this.temp = {
        _serialized: '',
        platform: '',
        password: '',
        user_id: ''
      }
      if (this.temp.user_id === '') {
        this.temp.user_id = this.projectUsers[0].id
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        table_name: this.table_name,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '640px'
          this.title = '添加'
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '640px'
          this.title = `确认要删除:${row._serialized}?`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '640px'
          this.title = `修改:${row._serialized}`
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined) this.temp[key] = row[key]
          })
          this.temp.id = row.id
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      _data.table_name = this.table_name
      switch (this.action) {
        case 'create':
          Post(_data
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('添加成功')
          })
          break
        case
          'delete'
          :
          Delete(_data.id, this.temp).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case
          'edit'
          :
          Put(_data.id, _data).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.top >>> .el-select .el-input {
  width: 350px;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
  /*margin: 168px auto !important;*/
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}
</style>
